package com.bo.shiro;

import com.bo.entity.User;
import com.bo.service.UserService;
import com.bo.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountRealm extends AuthorizingRealm {

    //注入jwtUtils才能获取用户声明claim
    @Autowired
    JwtUtils jwtUtils;

    //注入UserService才能调用业务层方法获取用户
    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //将认证标志强转为Jwt标志
        JwtToken jwtToken = (JwtToken)authenticationToken;

        //通过jwt标志获取用户声明，用户声明存储了用户信息
        Claims claim = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal());

        //获取用户编号
        long userId = Long.parseLong(claim.getSubject());

        //调用service层业务获取用户
        User user = userService.getById(userId);
        if(user == null){
            throw new UnknownAccountException("账户不存在！");
        }

        if(user.getStatus() == -1){
            throw new LockedAccountException("账户已被锁定！");
        }

        //新建账户信息类
        AccountProfile accountProfile = new AccountProfile();
        //将获取的用户中的特定属性值复制到accountProfile中
        BeanUtils.copyProperties(user, accountProfile);

        System.out.println("---------------------------");

        return new SimpleAuthenticationInfo(accountProfile, jwtToken.getCredentials(), getName());
    }
}
